<template>
  <div class="medicine">
    <!----------- Breadcrumb 面包屑 ---------------->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>医院后台</el-breadcrumb-item>
      <el-breadcrumb-item>药品管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 选择器--药品 -->
    <div class="block">
      <el-input v-model="searchText" placeholder="搜索药品信息（药品名字 / 药品ID)" style="width: 250px"></el-input>
      <el-button type="primary" @click="search(1)">搜索</el-button>
      <el-button type="primary" @click="search(2)">撤回</el-button>
    </div>

    <!--------------- 卡片部分 -- 显示信息 --------------->
    <el-card shadow="never" border="false">
      <!----- 卡片头部 ------>
      <template #header>
        <div class="header">
          <span>共 {{ newDrugs.length }} 条记录</span>
          <el-button icon="el-icon-plus" size="small" type="primary" @click="openDrawer('add')">添加药品信息</el-button>
        </div>
      </template>

      <!----- 卡片的内容 ----->
      <el-table
        :data="newDrugs.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
        style="width: 100%"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        @filter-change="filterTagTable"
      >
        <!--- 药品信息 --->
        <el-table-column type="expand" label="详细信息" width="140px" :default-sort="{ prop: 'drugID', order: 'descending' }">
          <template slot-scope="props">
            <!-- 详细信息部分 -->
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="药品编号：">
                <span>{{ props.row.drugID }}</span>
              </el-form-item>
              <el-form-item label="药品名称：">
                <span>{{ props.row.name }}</span>
              </el-form-item>
              <el-form-item label="药品规格：">
                <span>{{ props.row.size }}</span>
              </el-form-item>
              <el-form-item label="药品类型：">
                <span>{{ props.row.type }}</span>
              </el-form-item>
              <el-form-item label="处方药：">
                <span>{{ props.row.OTC }}</span>
              </el-form-item>
              <el-form-item label="供应商编号：">
                <span>{{ props.row.supplierID }}</span>
              </el-form-item>
              <el-form-item label="售价：">
                <span>{{ props.row.price }}</span>
              </el-form-item>
              <el-form-item label="保质期：">
                <span>{{ props.row.shelfLife }}</span>
              </el-form-item>
              <el-form-item label="入库时间：">
                <span>{{ props.row.day }}</span>
              </el-form-item>
              <el-form-item label="所处货架：">
                <span>{{ props.row.ShelfID }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="药品编号" prop="drugID" sortable> </el-table-column>
        <el-table-column label="药品名称" prop="name"> </el-table-column>
        <el-table-column label="库存" prop="count"> </el-table-column>
        <el-table-column prop="status" label="库存状态" width="100" :column-key="'status'" :filters="statusDate" filter-placement="bottom-end">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === '库存充足' ? 'primary' : scope.row.status === '库存紧张' ? 'warning' : 'danger'" disable-transitions>{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>

        <!--- 基本操作 --->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div class="actions">
              <!-- 修改信息 -->
              <i class="el-icon-edit-outline" @click="openDrawer('edit', scope.row)"></i>
              <!-- 删除信息 -->
              <i class="el-icon-delete" @click="$store.commit('medicine/deleteDugs', scope.$index)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页： handleSizeChange:每页条数变化触发；handleCurrentChange：当前页改变触发；current-page：当前页；page-size：每页显示多少条；layout：排版布局-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="newDrugs.length"
      >
      </el-pagination>
    </el-card>

    <!-- 添加/编辑抽屉： title：标题； :visible.sync 控制打开/关闭；direction：控制打开方向；before-close：关闭之前执行的方法；size：控制大小-->
    <el-drawer :title="drawerTitle" :visible.sync="drawer" :direction="direction" :before-close="handleClose" size="48%">
      <!--  抽屉内容部分：添加、修改操作===》表单  -->
      <el-form label-width="auto" :model="addDrug" :rules="rules" ref="addDrug">
        <el-form-item label="药品ID:" prop="drugID"
          ><el-input v-model="addDrug.drugID" placeholder="格式：YCP-202405XXXX" :readonly="flag" @blur="verifyInput('药品ID', addDrug.drugID)"></el-input
        ></el-form-item>
        <el-form-item label="药品名称:" prop="name"><el-input v-model="addDrug.name"></el-input></el-form-item>
        <!-- gutter:栅格间隔; span:栅格占据的列数-->
        <el-row :gutter="0">
          <el-col :span="8"
            ><el-form-item label="规格:" prop="size"><el-input v-model="addDrug.size"></el-input></el-form-item
          ></el-col>
          <el-col :span="8"
            ><el-form-item label="类型:" prop="type"><el-input v-model="addDrug.type"></el-input></el-form-item
          ></el-col>
          <el-col :span="7" :offset="1"
            ><el-form-item label="处方药:" placeholder="是/否" prop="OTC"><el-input v-model="addDrug.OTC"></el-input></el-form-item
          ></el-col>
          <el-col :span="13"
            ><el-form-item label="供应商ID:" placeholder="格式：SYXXX" prop="OTC"><el-input v-model="addDrug.supplierID"></el-input></el-form-item
          ></el-col>
          <el-col :span="8" :offset="3"
            ><el-form-item label="售价:" prop="price"><el-input v-model="addDrug.price"></el-input></el-form-item
          ></el-col>
          <el-col :span="13">
            <el-form-item label="入库时间:" prop="day"><el-input v-model="addDrug.day" placeholder="格式：XXXX-X-X   XX:XX" @blur="verifyInput('入库时间', addDrug.day)"></el-input> </el-form-item>
          </el-col>
          <el-col :span="8" :offset="3">
            <el-form-item label="保质期:" prop="shelfLife"><el-input v-model="addDrug.shelfLife"></el-input></el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="货架ID:" prop="ShelfID"><el-input v-model="addDrug.ShelfID" placeholder="格式：G-XX-XXX" @blur="verifyInput('货架ID', addDrug.ShelfID)"></el-input></el-form-item>
          </el-col>
          <el-col :span="8" :offset="3">
            <el-form-item label="库存:" prop="count"><el-input v-model="addDrug.count"></el-input></el-form-item>
          </el-col>
        </el-row>
        <br /><br />
        <!-- 操作部分：添加/取消 -->
        <el-form-item>
          <el-col :span="8" :offset="5">
            <el-button type="primary" @click="onSubmit()">立即添加</el-button>
          </el-col>
          <el-button @click="handleClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
//导入 vuex 中辅助函数
import { mapState } from 'vuex';

export default {
  name: 'MedicineIndex',

  data() {
    return {
      searchText: '', //搜索信息
      newDrugs: [], //存放store引用过来的数据drugs
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示的条数
      selectdata: { status: [] }, //存放筛选的条件
      newData: [], //辅助筛选
      twoData: [], //辅助筛选
      statusDate: [
        { text: '库存充足', value: '库存充足' },
        { text: '库存紧张', value: '库存紧张' },
        { text: '无库存', value: '无库存' },
      ], //存放筛选条件
      drawer: false, //false-关闭抽屉，true-打开抽屉
      direction: 'rtl', //打开方式：从右往左
      drawerType: '', //打开抽屉后的操作类型
      //添加药品的对象属性
      addDrug: {
        drugID: '',
        name: '',
        size: '',
        type: '',
        OTC: '',
        supplierID: '',
        price: '',
        shelfLife: '',
        day: '',
        ShelfID: '',
        count: '',
        status: '',
      },
      //表单验证
      rules: {
        drugID: [{ required: true, message: '药品ID不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '药品名称不能为空', trigger: 'blur' }],
        drugID: [{ required: true, message: '药品ID不能为空', trigger: 'blur' }],
        size: [{ required: true, message: '规格不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
        shelfLife: [{ required: true, message: '保质期不能为空', trigger: 'blur' }],
        day: [{ required: true, message: '入库时间不能为空', trigger: 'blur' }],
        ShelfID: [{ required: true, message: '货架编号不能为空', trigger: 'blur' }],
      },
      flag: false, //辅助表单禁用
    };
  },

  //挂载渲染页面
  mounted() {
    this.newDrugs = this.drugs;
    localStorage.setItem('table', JSON.stringify(this.newDrugs)); //存储到本地
  },

  computed: {
    ...mapState('medicine', ['drugs']), //引入store中medicine模块的state数据 drugs

    // 打开抽屉时显示的标题
    drawerTitle() {
      if (this.drawerType === 'add') return '添加药品信息';
      else if (this.drawerType === 'edit') return '编辑药品信息';
    },
  },

  methods: {
    //验证表单输入格式
    verifyInput(message, value) {
      let regex;
      console.log(value);
      if (message === '药品ID') regex = /^YCP-\d{8}$/;
      else if (message === '入库时间') regex = /^20\d{2}-\d{2}-\d{2}\s\d{2}:\d{2}$/;
      else regex = /^G-\d{2}-\d{3}$/;
      if (!regex.test(value) && value !== '') this.$message.error(message + '格式有误!');
    },

    //搜索信息
    search(id) {
      if (id === 1 && this.searchText) {
        // console.log("搜索操作")
        this.newDrugs = this.drugs.filter(item => item.name.includes(this.searchText) || item.drugID.includes(this.searchText));
        if (this.newDrugs.length < 1) this.$message.error('未搜索到相关数据！请检查是否输入有误。');
      } else if (id === 2 && !this.searchText) {
        console.log('撤销操作');
        this.newDrugs = this.drugs;
        console.log(this.newDrugs);
      }
      this.searchText = '';
    },

    //更新每页显示数量: 每页多少条发生变化后触发
    handleSizeChange(val) {
      this.pageSize = val;
    },

    //更新页码: 当前页码变化后促发
    handleCurrentChange(val) {
      this.currentPage = val; //
    },

    //分页器情况下进行条件筛选
    filterTagTable(filters) {
      this.twoData = []; //初始化一个空数组
      this.selectdata[String(Object.keys(filters))] = filters[String(Object.keys(filters))]; //将传入的筛选条件 filters 存储到 selectdata 对象中
      this.newData = JSON.parse(localStorage.getItem('table')); //从本地存储中获取名为 'table' 的数据，并将其解析为 JavaScript 对象，存储到 newData 变量中
      // console.log(this.selectdata)
      if (this.selectdata[Object.keys(this.selectdata)].length <= 1) {
        //判断当前筛选条件的值的数量是否小于等于1。
        for (let k = 0; k < this.selectdata[Object.keys(this.selectdata)].length; k++) {
          //遍历当前筛选条件的值。
          for (let i = 0; i < this.newData.length; i++) {
            //遍历 newData 数组
            //判断当前筛选条件的值是否不等于 newData 数组中的对应元素
            if (this.selectdata[Object.keys(this.selectdata)][k] !== this.newData[i][String(Object.keys(this.selectdata))]) {
              this.newData.splice(i, 1); //如果不等于，则从 newData 数组中删除该元素
              i--; //将 i 减 1，以便下一次循环时仍然指向正确的索引
            }
          }
        }
      } else {
        //如果当前筛选条件的值的数量大于1
        console.log('选择了多个');
        this.twoData = []; //初始化一个空数组
        for (let k = 0; k < this.selectdata[Object.keys(this.selectdata)].length; k++) {
          //遍历当前筛选条件的值
          for (let i = 0; i < this.newData.length; i++) {
            //遍历 newData 数组
            //判断当前筛选条件的值是否等于 newData 数组中的对应元素
            if (this.selectdata[Object.keys(this.selectdata)][k] === this.newData[i][String(Object.keys(this.selectdata))]) {
              this.twoData.push(this.newData[i]); //如果等于，则将该元素添加到 twoData 数组中
            }
          }
        }
        if (this.twoData.length !== 0) {
          //如果 twoData 数组不为空
          this.newData = []; //初始化一个newData[]数组
          for (let i = 0; i < this.twoData.length; i++) {
            //遍历 twoData 数组
            this.newData.push(this.twoData[i]); //将 twoData 数组中的元素添加到 newData 数组中
          }
        }
      }
      // console.log(this.newData);
      this.newDrugs = this.newData;
    },

    //打开抽屉操作
    openDrawer(type, drug) {
      // type ==> add | edit
      // console.log(type);
      console.log('打开抽屉');
      this.drawerType = type; //修改drawerType变量
      if (type === 'edit') {
        this.addDrug = { ...drug }; //编辑情况下回显数据
        this.flag = true;
      } else this.flag = false;
      this.drawer = true; //修改抽屉drawer布尔值，使其为true
    },

    // 关闭抽屉之前执行的方法
    handleClose() {
      console.log('抽屉关闭');
      this.addDrug = {
        // 彻底重置 addDrug 数据
        drugID: '',
        name: '',
        size: '',
        type: '',
        OTC: '',
        supplierID: '',
        price: '',
        shelfLife: '',
        day: '',
        ShelfID: '',
        count: '',
        status: '',
      };
      this.drawer = false;
    },

    //提交表单
    onSubmit() {
      // 表单.validate(valid => {  /* valid=true验证通过；valid=false验证不通过 */  })
      this.$refs.addDrug.validate(valid => {
        if (valid && this.verifyInput()) {
          // 验证通过，可以提交数据
          //判断库存是否充足
          if (this.addDrug.count >= 50) this.addDrug.status = '库存充足';
          else if (this.addDrug.count === 0 || this.addDrug.count === '') {
            this.addDrug.count = 0;
            this.addDrug.status = '无库存';
          } else this.addDrug.status = '库存紧张';
          // console.log(this.addDrug);

          //传药品的数据
          if (this.drawerType == 'add') {
            //添加药品
            this.$store
              .dispatch('medicine/onSubmit', { data: this.addDrug, type: this.drawerType })
              .then(() => {
                this.$message.success('添加药品信息成功!');
              })
              .catch(error => {
                //错误处理
                this.$message.error('添加药品信息失败' + error.message);
              });
          } else {
            //编辑药品
            this.$store
              .dispatch('medicine/onSubmit', { data: this.addDrug, type: this.drawerType })
              .then(() => {
                this.$message.success('修改药品信息成功!');
              })
              .catch(error => {
                //错误处理
                this.$message.error('修改药品信息失败' + error.message);
              });
          }
          this.handleClose();
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.medicine {
  //Breadcrumb 面包屑样式
  .el-breadcrumb {
    margin-top: 10px;
    margin-bottom: 25px;
  }
  .block {
    .el-button {
      margin-left: 10px;
    }
  }
  //卡片部分样式
  .el-card {
    margin-top: 25px;
    //卡片头部样式
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-right: 16px;
    }
    .el-table {
      //表格样式
      .demo-table-expand {
        padding: 0 40px;
        margin: 0 50px;
        font-size: 0;
      }
      .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
      }
      .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%; //每行显示数量
      }

      //插槽内图标样式
      .actions {
        font-size: 18px; //图标大小
        display: flex;
        justify-content: space-around;
        color: #666;
        //交互效果
        > i:hover {
          color: rgba(114, 124, 245, 1); //鼠标滑动时，图标颜色改变
          cursor: pointer; //鼠标移动显示小手
        }
      }
    }

    //分页样式
    .el-pagination {
      margin-top: 20px; //上边距
      text-align: center; //字体居中
    }
  }
  //抽屉部分样式
  .el-drawer {
    .el-form {
      padding: 0 30px;
    }
  }
}
</style>